import { addBriefing } from '@/services/api/api-monitor-briefing';
import {
  EditableProTable,
  ProColumns,
  ProFormDigit,
  ProFormSelect,
  ProFormTimePicker,
} from '@ant-design/pro-components';
import ProForm, { DrawerForm, ProFormText } from '@ant-design/pro-form';
import { Button, Card, message } from 'antd';
import dayjs from 'dayjs';
import React, { useState } from 'react';
interface AddAudioVisualProps {
  onRefurbish: () => void;
}
const AddAudioVisual: React.FC<AddAudioVisualProps> = ({ onRefurbish }) => {
  const [dataSourceAbjc, setDataSourceAbjc] = useState([]);
  const [editableKeysAbjc, setEditableRowKeysAbjc] = useState<React.Key[]>([]);
  const [dataSourceGgjc, setDataSourceGgjc] = useState([]);
  const [editableKeysGgjc, setEditableRowKeysGgjc] = useState<React.Key[]>([]);
  const [yearOption, setYearOption] = useState([
    {
      label: '2020年',
      value: '2020',
    },
    {
      label: '2021年',
      value: '2021',
    },
    {
      label: '2022年',
      value: '2022',
    },
    {
      label: '2023年',
      value: '2023',
    },
    {
      label: '2024年',
      value: '2024',
    },
    {
      label: '2025年',
      value: '2025',
    },
  ]);
  const [timeOption, setTimeOption] = useState([
    {
      label: '第1期',
      value: '1',
    },
    {
      label: '第2期',
      value: '2',
    },
    {
      label: '第3期',
      value: '3',
    },
    {
      label: '第4期',
      value: '4',
    },
    {
      label: '第5期',
      value: '5',
    },
    {
      label: '第6期',
      value: '6',
    },
    {
      label: '第7期',
      value: '7',
    },
    {
      label: '第8期',
      value: '8',
    },
    {
      label: '第9期',
      value: '9',
    },
    {
      label: '第10期',
      value: '10',
    },
    {
      label: '第11期',
      value: '11',
    },
    {
      label: '第12期',
      value: '12',
    },
  ]);

  const [selectTime, setSelectTime] = useState<number>(6);
  const columnsAbjc: ProColumns[] = [
    {
      title: '事故单位',
      dataIndex: 'unit',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '事故频道',
      dataIndex: 'channel',
    },
    {
      title: '事故次数',
      key: 'count',
      dataIndex: 'count',
      valueType: 'digit',
      fieldProps: {
        style: { width: '100%' },
      },
    },
    {
      title: '事故时长',
      dataIndex: 'duration',
      valueType: 'time',
      fieldProps: {
        variant: 'outlined',
        showNow: false,
        style: { width: '100%' },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 250,
      render: () => {
        return null;
      },
    },
  ];
  const columnsGgjc: ProColumns[] = [
    {
      title: '频道名称',
      dataIndex: 'channel',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '监测日期',
      dataIndex: 'date',
      valueType: 'date',
      fieldProps: {
        style: { width: '100%' },
      },
    },
    {
      title: '商业广告超时时段（个）',
      key: 'timeout',
      dataIndex: 'timeout',
      valueType: 'digit',
      fieldProps: {
        style: { width: '100%' },
      },
    },
    {
      title: '违规播出广告（个）',
      key: 'shoppingAds',
      dataIndex: 'shoppingAds',
      valueType: 'digit',
      fieldProps: {
        style: { width: '100%' },
      },
    },
    {
      title: '违规医药广告（个）',
      key: 'medicalAds',
      dataIndex: 'medicalAds',
      valueType: 'digit',
      fieldProps: {
        style: { width: '100%' },
      },
    },
    {
      title: '合计',
      key: 'total',
      dataIndex: 'total',
      width: 130,
      valueType: 'digit',
      fieldProps: {
        style: { width: '100%' },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 80,
      render: () => {
        return null;
      },
    },
  ];
  const formatTime = (time) => {
    if (!time) {
      return null; // 如果没有传入时间，返回 null
    }

    // 判断传入的时间字符串格式
    let dayjsTime;
    if (time.includes(':')) {
      // 如果包含冒号，尝试将其视为时分秒或完整日期时间
      if (time.length === 8) {
        // 形如 "HH:mm:ss"
        dayjsTime = dayjs(`1970-01-01 ${time}`, 'YYYY-MM-DD HH:mm:ss'); // 使用一个默认日期
      } else {
        // 形如 "YYYY-MM-DD HH:mm:ss"
        dayjsTime = dayjs(time, 'YYYY-MM-DD HH:mm:ss');
      }
    } else {
      console.error('Invalid time format:', time);
      return null; // 如果格式不正确，返回 null
    }

    // 检查 dayjs 对象是否有效
    if (!dayjsTime.isValid()) {
      console.error('Invalid time value:', time);
      return null;
    }

    // 返回格式化后的时分秒
    return dayjsTime.format('HH:mm:ss');
  };
  return (
    <DrawerForm
      title="录入"
      // layout='horizontal'
      drawerProps={{
        destroyOnClose: true,
        width: '70%',
      }}
      trigger={<Button type="primary">手动录入</Button>}
      onOpenChange={(open) => {
        if (open) {
        } else {
          setDataSourceAbjc([]);
          setDataSourceGgjc([]);
        }
      }}
      onFinish={async (values) => {
        const {
          totalStopDuration,
          lastMonthTotalStopDuration,
          samePeriodLastYearTotalStopDuration,
          totalDuration,
          ...restValues
        } = values;
        console.log(
          totalStopDuration,
          lastMonthTotalStopDuration,
          samePeriodLastYearTotalStopDuration,
        );

        const formattedTotalStopDuration = formatTime(totalStopDuration);
        const formattedLastMonthTotalStopDuration = formatTime(lastMonthTotalStopDuration);
        const formattedSamePeriodLastYearTotalStopDuration = formatTime(
          samePeriodLastYearTotalStopDuration,
        );
        const formattedTotalDuration = formatTime(totalDuration);
        const response = await addBriefing({
          ...restValues,
          incidentData: dataSourceAbjc,
          dataGg: dataSourceGgjc,
          totalStopDuration: formattedTotalStopDuration,
          lastMonthTotalStopDuration: formattedLastMonthTotalStopDuration,
          samePeriodLastYearTotalStopDuration: formattedSamePeriodLastYearTotalStopDuration,
          totalDuration: formattedTotalDuration,
        });

        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
        }
        return true;
      }}
    >
      <ProForm.Group>
        <ProFormSelect
          label="年份"
          name="year"
          rules={[{ required: true, message: '请选择年限' }]}
          placeholder="选择年限"
          fieldProps={{
            options: yearOption,
            style: {
              width: 300,
            },
            removeIcon: true,
            allowClear: true,
            showSearch: true,
            maxTagCount: 'responsive',
          }}
        />
        <ProFormSelect
          label="期数"
          name="time"
          placeholder="选择期数"
          rules={[{ required: true, message: '请选择期数' }]}
          fieldProps={{
            options: timeOption,
            style: {
              width: 300,
            },
            removeIcon: true,
            allowClear: true,
            showSearch: true,
            maxTagCount: 'responsive',
            onClear() {
              setSelectTime('1');
            },
            onChange(value, selectOptions) {
              setSelectTime(value);
            },
          }}
        />
      </ProForm.Group>
      <Card title="安播监测">
        <ProForm.Group>
          <ProFormSelect
            label="月份"
            name="month"
            valueEnum={{
              1: '一月',
              2: '二月',
              3: '三月',
              4: '四月',
              5: '五月',
              6: '六月',
              7: '七月',
              8: '八月',
              9: '九月',
              10: '十月',
              11: '十一月',
              12: '十二月',
            }}
            rules={[{ required: true, message: '请输入月份' }]}
          />
          <ProFormDigit
            name="stopIncidentCount"
            label="停播事故次数"
            // rules={[{ required: true, message: '请输入停播事故次数' }]}
          />
          <ProFormDigit
            name="majorIncidentCount"
            label="重大事故次数"
            // rules={[{ required: true, message: '请输入重大事故次数' }]}
          />
          <ProFormTimePicker
            name="totalStopDuration"
            label="总停播时长"
            // rules={[{ required: true, message: '请输入总停播时长' }]}
            fieldProps={{
              format: 'HH:mm:ss',
              variant: 'outlined',
              showNow: false,
            }}
          />
          <ProFormDigit
            name="responsibilityIncidents"
            label="责任事故次数"
            // rules={[{ required: true, message: '请输入责任事故次数' }]}
          />

          <ProFormText
            name="technicalIncidents"
            label="技术事故次数"
            // rules={[{ required: true, message: '请输入技术事故次数' }]}
          />

          <ProFormDigit
            name="lastMonthStopIncidentCount"
            label="上月停播事故次数"
            // rules={[{ required: true, message: '请输入上月停播事故次数' }]}
          />
          <ProFormDigit
            name="lastMonthMajorIncidentCount"
            label="上月重大事故次数"
            // rules={[{ required: true, message: '请输入上月重大事故次数' }]}
          />
          <ProFormTimePicker
            name="lastMonthTotalStopDuration"
            label="上月总停播时长"
            // rules={[{ required: true, message: '请输入上月总停播时长' }]}
            fieldProps={{
              variant: 'outlined',
              // format: 'HH:mm:ss',
              showNow: false,
            }}
          />

          <ProFormText
            name="samePeriodLastYearStopIncidentCount"
            label="去年同期停播事故次数"
            // rules={[{ required: true, message: '请输入去年同期停播事故次数' }]}
          />
          <ProFormDigit
            name="samePeriodLastYearMajorIncidentCount"
            label="去年同期重大事故次数"
            // rules={[{ required: true, message: '请输入去年同期重大事故次数' }]}
          />
          <ProFormTimePicker
            name="samePeriodLastYearTotalStopDuration"
            label="去年同期总停播时长"
            fieldProps={{
              variant: 'outlined',
              // format: 'HH:mm:ss',
              showNow: false,
            }}
            // rules={[{ required: true, message: '请输入去年同期总停播时长' }]}
          />
          <ProFormDigit
            name="totalChannel"
            label="事故单位/频道数"
            // rules={[{ required: true, message: '请输入事故单位/频道数' }]}
          />
          <ProFormDigit
            name="totalCount"
            label="总事故次数"
            // rules={[{ required: true, message: '请输入总事故次数' }]}
          />

          <ProFormTimePicker
            name="totalDuration"
            label="总事故时长"
            fieldProps={{
              variant: 'outlined',
              // format: 'HH:mm:ss',
              showNow: false,
            }}
            // rules={[{ required: true, message: '请输入总事故时长' }]}
          />
        </ProForm.Group>
        <EditableProTable
          ghost
          headerTitle="事故单位信息"
          columns={columnsAbjc}
          rowKey="id"
          value={dataSourceAbjc}
          onChange={setDataSourceAbjc}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            record: () => ({
              id: Date.now(),
            }),
          }}
          editable={{
            type: 'multiple',
            editableKeys: editableKeysAbjc,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete];
            },
            onValuesChange: (record, recordList) => {
              setDataSourceAbjc(recordList);
            },
            onChange: setEditableRowKeysAbjc,
          }}
        />
      </Card>
      <Card title="广告监测" style={{ marginTop: 20 }}>
        <ProForm.Group>
          <ProFormText
            name="publicServiceAdsCount"
            label="公益广告条数"
            // rules={[{ required: true, message: '请输入公益广告条数' }]}
          />
          {/* <ProFormTimePicker
                        name="publicServiceAdsDuration"
                        label="公益广告时长"
                        rules={[{ required: true, message: '请输入公益广告时长' }]}
                        fieldProps={{
                            variant: "outlined",
                            showNow: false,
                            // 这里设置最大值，50小时 = 50 * 60 * 60 * 1000 毫秒
                        }}
                    /> */}
          <ProFormText
            name="publicServiceAdsDuration"
            label="公益广告时长（例如：50小时10分10秒）"
            // rules={[{ required: true, message: '请输入公益广告时长' }]}
          />
          <ProFormText
            name="commercialAdsCount"
            label="商业广告条数"
            // rules={[{ required: true, message: '请输入公益广告条数' }]}
          />
          <ProFormText
            name="commercialAdsDuration"
            label="商业广告时长（例如：50小时10分10秒）"
            // rules={[{ required: true, message: '请输入商业广告时长' }]}
          />
          <ProFormDigit
            name="violationsTotal"
            label="违规行为总数"
            // rules={[{ required: true, message: '请输入违规行为总数' }]}
          />

          <ProFormDigit
            name="violationsShoppingAds"
            label="违规播出电视购物短片广告数"
            // rules={[{ required: true, message: '请输入违规播出电视购物短片广告数' }]}
          />

          <ProFormDigit
            name="violationsMedicalAds"
            label="违规医药广告数"
            // rules={[{ required: true, message: '请输入违规医药广告数' }]}
          />
          <ProFormDigit
            name="violationsCommercialTimeout"
            label="商业广告超时播出时段数"
            // rules={[{ required: true, message: '请输入商业广告超时播出时段数' }]}
          />
        </ProForm.Group>
        <EditableProTable
          ghost
          headerTitle="频道信息"
          columns={columnsGgjc}
          rowKey="id"
          value={dataSourceGgjc}
          onChange={setDataSourceGgjc}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            record: () => ({
              id: Date.now(),
            }),
          }}
          editable={{
            type: 'multiple',
            editableKeys: editableKeysGgjc,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete];
            },
            onValuesChange: (record, recordList) => {
              setDataSourceGgjc(recordList);
            },
            onChange: setEditableRowKeysGgjc,
          }}
        />
      </Card>
      <Card title="视听新媒体监测" style={{ marginTop: 20 }}>
        <ProForm.Group>
          <ProFormDigit
            name="totalUnits"
            label="持证单位总数"
            // rules={[{ required: true, message: '请输入持证单位总数' }]}
          />
          <ProFormDigit
            name="holdCertificateViolations"
            label="持证单位违规情况"
            // rules={[{ required: true, message: '请输入违规内容' }]}
          />
          <ProFormDigit
            name="renewed"
            label="需换证机构网站"
            // rules={[{ required: true, message: '请输入需换证机构网站' }]}
          />

          <ProFormDigit
            name="changeCertificateViolations"
            label="换证机构违规情况"
            // rules={[{ required: true, message: '请输入违规内容' }]}
          />
        </ProForm.Group>
      </Card>
      <Card title="IPTV 频道监测" style={{ marginTop: 20 }}>
        <ProForm.Group>
          <ProFormDigit
            name="telecomChannels"
            label="电信频道数"
            // rules={[{ required: true, message: '请输入电信频道数' }]}
          />
          <ProFormDigit
            name="unicomChannels"
            label="联通频道数"
            // rules={[{ required: true, message: '请输入联通频道数' }]}
          />
          <ProFormDigit
            name="mobileChannels"
            label="移动频道数"
            // rules={[{ required: true, message: '请输入移动频道数' }]}
          />
          <ProFormDigit
            name="monitoredPrograms"
            label="人工监看点播节目数"
            // rules={[{ required: true, message: '请输入人工监看点播节目数' }]}
          />
          <ProFormDigit
            name="violations"
            label="违规情况"
            // rules={[{ required: true, message: '请输入违规内容' }]}
          />
        </ProForm.Group>
      </Card>
      {/* <ProForm.Group>
                <ProFormSelect
                    name="types"
                    label="类型"
                    width="xl"
                    placeholder="请选择关键词类型"
                    fieldProps={{
                        mode: 'multiple',
                    }}
                    rules={[{ required: true, message: '请选择关键词类型' }]}
                    options={[
                        {
                            label: '人名',
                            value: 1,
                        },
                        {
                            label: '地名',
                            value: 2,
                        },
                        {
                            label: '机构',
                            value: 3,
                        },
                        {
                            label: '其他',
                            value: 4,
                        },
                    ]}
                />
            </ProForm.Group> */}
    </DrawerForm>
  );
};
export default AddAudioVisual;
